package com.rxst.msg.utils;

import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Properties;

/**
 * @author zgs
 */
public class MacUtil {

    public static void main(String[] args) {
        getMachineCode();
    }

    private static String getMac() {
        try {
            Enumeration<NetworkInterface> el = NetworkInterface
                    .getNetworkInterfaces();
            while (el.hasMoreElements()) {
                byte[] mac = el.nextElement().getHardwareAddress();
                if (mac == null)
                    continue;
                return bytesToHexString(mac);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return null;
    }

    public static StringBuffer getMachineCode() {
        StringBuffer buffer = new StringBuffer();
        String mac = getMac();
        // 0 mac地址
        buffer.append(mac + ",");
        Properties props = System.getProperties();
        String javaVersion = props.getProperty("java.version");
        // 1 javaVersion
        buffer.append(javaVersion + ",");
        String javaVMVersion = props.getProperty("java.vm.version");
        // 2 VMVersion
        buffer.append(javaVMVersion + ",");
        String osVersion = props.getProperty("os.version");
        // 3 osVersion
        buffer.append(osVersion + ",");
        return buffer;
    }

    private final static char[] hexArray = "0123456789ABCDEF".toCharArray();

    public static String bytesToHexString(byte... bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }
}
